package com.signway.javaui.slice.component.listcontainer.provider;

import com.signway.javaui.ResourceTable;
import com.signway.javaui.slice.component.listcontainer.domain.Item;
import com.signway.javaui.utils.SwLog;
import ohos.agp.components.*;
import ohos.app.Context;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class ItemProvider extends BaseItemProvider {

    Context context;
    ArrayList<Item> mItemList;
    Map<Integer, Integer> map = new HashMap<>();

    public ItemProvider(Context context, ArrayList<Item> mItemList) {
        this.mItemList = mItemList;
        this.context = context;
    }

    private int getAddressId(int address) {
        if (map == null) {
            map.put(address, map.size() + 1);
        } else if (!map.containsKey(address)) {
            map.put(address, map.size() + 1);
        }
        return map.get(address);
    }

    @Override
    public int getCount() {
        return mItemList.size();
    }

    @Override
    public Object getItem(int i) {
        if (mItemList != null && i >= 0 && i < mItemList.size()) {
            return mItemList.get(i);
        }
        return null;
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
        DirectionalLayout directionalLayout;

        if (component != null) {
            directionalLayout = (DirectionalLayout) component;
            SwLog.info("复用" + getAddressId(System.identityHashCode(directionalLayout)));
        } else {
            directionalLayout = (DirectionalLayout) LayoutScatter
                    .getInstance(context)
                    .parse(ResourceTable.Layout_list_container_item, null, false);
            SwLog.info("新建" + getAddressId(System.identityHashCode(directionalLayout)));
        }

        Text itemTitle = (Text) directionalLayout.findComponentById(ResourceTable.Id_item_title_text);
        Text itemContent = (Text) directionalLayout.findComponentById(ResourceTable.Id_item_content_text);
        Text itemDate = (Text) directionalLayout.findComponentById(ResourceTable.Id_item_date_text);

        itemTitle.setText(mItemList.get(i).getTitle());
        itemContent.setText(mItemList.get(i).getContent());
        itemDate.setText(mItemList.get(i).getDate());

        return directionalLayout;
    }
}
